package com.ezops.util;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Map the {@link com.ezops.util.Report} to the destination class.
 * 
 * @author vgaurav
 * 
 */
public class ReportMapper implements IReportMapper {

	private static final Logger logger = LoggerFactory
			.getLogger(ReportMapper.class);

	@Override
	public <T> List<T> map(Class<T> classType, Report report) throws ReportMappingException {
		logger.trace("Mapping to the destination type {}", classType);
		// Add pre conditions - TODO
		List<T> listDestinations = new ArrayList<>();

		Iterator<Report.Row> rows = report.iterator();
		while (rows.hasNext()) {
			Report.Row row = rows.next();
			try {
				T destinationInstance = classType.newInstance();
				Field[] fields = classType.getDeclaredFields();

				for (Field field : fields) {
					ReportField reportField = field
							.getAnnotation(ReportField.class);
					if (reportField == null) {
						logger.debug(
								"The field {} doesn't have ReportField annotation, skipping the field",
								field.getName());
						continue;
					}
					int position = reportField.pos();
					field.setAccessible(true);
					field.set(destinationInstance, removeDoubleQuotes(row.getValue(position)));

				}
				listDestinations.add(destinationInstance);

			} catch (InstantiationException | IllegalAccessException e) {
				logger.error(
						"Error while mapping the report to model {}, reason - {}",
						classType.getName(), e.getMessage());
				throw new ReportMappingException(e.getMessage());
			}
		}
		return listDestinations;
	}
	
	private String removeDoubleQuotes(String value){
		String checkValue = (value == null) ? "" : value;
		return checkValue.replaceAll("^\"|\"$", "");
	}
}
